using OpenBlock.Block;
using OpenBlock.Math;
using OpenBlock.Properties;
using OpenBlock.Utils;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.UI;

namespace OpenBlock
{
    public class AtlasManager : MonoBehaviour
    {
        public RenderTexture genAtlas;
        public SingleCube actor;
        public Camera atlasCamera;

        private Texture2D atlas;
        private Dictionary<BlockId, Sprite> blockItems;



        private int curCol, curRow;

        private void Start()
        {
            blockItems = new Dictionary<BlockId, Sprite>();
            atlas = new Texture2D(genAtlas.width * 16, genAtlas.height * 16);
            atlas.filterMode = FilterMode.Point;
            curCol = 0;
            curRow = 0;

            CreateAtlas();
        }

        public void CreateAtlas()
        {
            AddAtlas(BlockId.Stone, new BlockState(BlockId.Stone));
            AddAtlas(BlockId.Grass, new BlockState(BlockId.Grass));
            AddAtlas(BlockId.CraftingTable, new BlockState(BlockId.CraftingTable).AddProperty("dir", new Property((byte)Direction.East)));
            AddAtlas(BlockId.Dirt, new BlockState(BlockId.Dirt));
            AddAtlas(BlockId.TNT, new BlockState(BlockId.TNT));
            AddAtlas(BlockId.Log, new BlockState(BlockId.Log).AddProperty("axis", new Property((byte)Axis.Y)));
            AddAtlas(BlockId.Furnance, new BlockState(BlockId.Furnance).AddProperty("dir", new Property((byte)Direction.East)));
        }

        public Sprite GetBlockItemIcon(BlockId id)
        {
            return blockItems.TryGetValue(id, out Sprite sprite) ? sprite : null;
        }

        private void AddAtlas(BlockId id, BlockState state)
        {
            var prev = RenderTexture.active;
            RenderTexture.active = genAtlas;

            actor.Rebuild(state);

            atlasCamera.Render();
            atlas.ReadPixels(new Rect(0, 0, genAtlas.width, genAtlas.height), curCol * genAtlas.width, curRow * genAtlas.height);
            atlas.Apply();

            blockItems.Add(id, Sprite.Create(atlas, new Rect(curCol * genAtlas.width, curRow * genAtlas.height, genAtlas.width, genAtlas.height), Vector2.one * 0.5f));

            curCol += 1;
            if (curCol >= 16)
            {
                curRow += 1;
                curCol = 0;
            }

            RenderTexture.active = prev;
        }
    }
}
